#include "DiffNormAlgo.h"

#include "DiffNorm.h"
#include "codetable/CombinedCodeTable.h"


const string DiffNormAlgo::NAME = "diffnorm";

DiffNormAlgo::DiffNormAlgo(CodeTable** combinedCTs, uint8 numSplits, Config* config) {
    mConfig = config;
    mReportIteration = false;
    mReportIterType = ReportAll;
    mLogFile = NULL;
    mWriteCTLogFile = config->Read<bool>("writeCTLogFile", true);
    mWriteReportFile = config->Read<bool>("writeReportFile", true);
    mWriteProgressToDisk = config->Read<bool>("writeProgressToDisk", true);
    mWriteLogFile = config->Read<bool>("writeLogFile", true);
    
    // DIFFNORM BOOK-KEEPING
    mCombinedCTs = combinedCTs;
    mNumDBSplits = numSplits;
}

DiffNormAlgo::~DiffNormAlgo() {
    for(uint32 i=0; i<mNumDBSplits; i++)
	delete mCombinedCTs[i];
    delete[] mCombinedCTs;
}

string DiffNormAlgo::GetShortName() { 
    return "a-ct";
}

DiffNormAlgo* DiffNormAlgo::CreateAlgo(ItemSetType isType, Config* config, uint8 numSplits) {
    return new DiffNorm(CreateCombinedCT(isType, numSplits), numSplits, config);
}

CodeTable** DiffNormAlgo::CreateCombinedCT(ItemSetType dataType, uint8 numSplits) {
    CodeTable** combinedCTs = new CodeTable*[numSplits];
    for (uint32 i=0; i<numSplits; i++) {
        if (dataType == BM128ItemSetType) {
            combinedCTs[i] = new CombinedCodeTable<BM128ItemSetType>();
        } else if (dataType == Uint16ItemSetType) {
            combinedCTs[i] = new CombinedCodeTable<Uint16ItemSetType>();
        } else if (dataType == BAI32ItemSetType) {
            combinedCTs[i] = new CombinedCodeTable<BAI32ItemSetType>();
        } else {
            THROW("Unable to create CodeTable. Unknown data type");
        }
    }
    return combinedCTs;
}

void DiffNormAlgo::BindCTsToDBs(Database **dbSplits, ItemSetType isType, uint32 maxCTElemLength) {
    // all the code tables will claim the ownership of the dbs here
    for (uint32 i=0; i<mNumDBSplits; i++) {
        mCombinedCTs[i]->UseThisStuff(dbSplits[i], isType, InitCTAlpha, maxCTElemLength);
    }
}
